package com.dd.keel.core.common.utils;

import java.io.*;
import java.nio.channels.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Keep one application instance 
 * @author Kevin.XU
 *
 */
public class ApplicationSingleton {
	
	final static private Logger LOGGER = LoggerFactory.getLogger(ApplicationSingleton.class);
	
	private String singletonLockFile = null;
	
    File f = null;
    RandomAccessFile raf = null;
    FileChannel fc = null;
    FileLock fl = null;
    FileWriter fr = null;	
	
	public ApplicationSingleton(String singletonLockFile)
	{
		this.singletonLockFile = singletonLockFile;
	}
	
	public boolean acquire() {
		try {
			f = new File(singletonLockFile);
			if(f.exists()) return false;
			raf = new RandomAccessFile(f, "rw");
			fr = new FileWriter(f);
			fr.write("singleton");
			fr.close();
			fr = null;
			fc = raf.getChannel();
			fl = fc.tryLock();
			return true;
		} catch (Exception ex) {
			//LOGGER.error(ex.getMessage(), ex);
			return false;
		}
	}

	public void dequire() {
		try {
			if (fr != null)
				fr.close();
			if (fl != null)
				fl.release();
			if (fc != null)
				fc.close();
			if (raf != null)
				raf.close();
			if (f != null)
				f.delete();
		} catch (Exception ex) {
			//LOGGER.error(ex.getMessage(), ex);
		}
	}

}
